import api from '../../../fetch/api'
import { deepCopyObj, deepCopyObjArray } from '../../../assets/js/help';

export default {
    data() {
        return {
            bigImgPath: '',
            importResult: '',
            importFile: {
                importFile: '',

            },
            importRules: {

            },
        }
    },
    created() {
        
    },
    computed: {
        inputParkstr: function (val) {
            if (this.SellCouponsModalData_detial.inputParks.length > 0) {
                return this.SellCouponsModalData_detial.inputParks.join(',')
            } else {
                return '';
            }
        },
        pay: function () {
            if (this.SellCouponsModalData.mainData.sellNum > 0) {
                this.SellCouponsModalData.mainData.totalMoney = this.SellCouponsModalData.mainData.sellNum * this.SellCouponsModalData.mainData.realPrice;
                this.SellCouponsModalData.mainData.sellMoney = this.SellCouponsModalData.mainData.totalMoney;
                return this.SellCouponsModalData.mainData.totalMoney;
            } else {
                return '';
            }
        }
    },
    methods: {
        // 优惠券下拉框搜索失去焦点
        couponBlurEvent(){
            this.SellCouponsModalData.placeholderStr = '请选择'
        },
        // 优惠券下拉框搜索获得焦点
        couponFocusEvent(){
            this.SellCouponsModalData.placeholderStr = '请选择/搜索优惠券/停车场'
        },
        // 所有优惠券
        allCoupon(val){
            let self = this
            self.SellCouponsModalData.select_list.forEach(elem=>{
                elem.isHidden = false
            })
            self.SellCouponsModalData.select_list.push({})
            this.$nextTick(()=>{
                self.SellCouponsModalData.select_list.pop()                
            })
        },
        // 搜索优惠券
        searchCoupon(val){
            let self = this
            self.SellCouponsModalData.select_list.forEach(elem=>{
                elem.isHidden = true
                if(!val || elem.label.indexOf(val)>-1){
                    elem.isHidden = false
                }
            })
            self.SellCouponsModalData.select_list.push({})
            this.$nextTick(()=>{
                self.SellCouponsModalData.select_list.pop()                
            })
        },
        prevPage(){
            this.SelectMerchantsModalData.pageNumber = this.SelectMerchantsModalData.pageNumber>1 ? this.SelectMerchantsModalData.pageNumber-1 : 1
        },
        nextPage(){
            this.SelectMerchantsModalData.pageNumber = this.SelectMerchantsModalData.pageNumber<this.SelectMerchantsModalData.total ? this.SelectMerchantsModalData.pageNumber+1 : this.SelectMerchantsModalData.total
        },
        getList() {
            this.getItemList();
        },
        SellCouponsModal_open() {
            var _this = this;
            _this.SellCouponsModalData = {
                placeholderStr: '请选择',
                couponName: '优惠券名称',
                select_list: [],
                mainData: {
                    coupon: '',
                    realPrice: '',
                    originalPrice: '',
                    traderName: '',
                    traderId: '',
                    totalAvilableToBuy: '',
                    maxBuyNum: '',
                    sellNum: '',
                    totalMoney: '',
                    sellMoney: '',
                    sellRemark: '',
                }
            };
            // 获取优惠券名称
            api.fetchGet('/coupon/sell/getCouponList2.do')
                .then(res => {
                    _this.SellCouponsModalData.select_list = []
                    if (res.data.rows.length > 0) {
                        _this.SellCouponsModalData.select_list = deepCopyObjArray(res.data.rows);
                        _this.SellCouponsModalData.select_list.forEach(elem => {
                            if(elem.parkNameList && Array.isArray(elem.parkNameList)){
                                elem.parkNameListStr = elem.parkNameList.join(' / ')
                            }else{
                                elem.parkNameListStr = ''
                            }
                            elem.label = elem.name+"-"+elem.parkNameListStr
                            elem.isHidden = false
                        });
                        _this.toOpenModal('SellCouponsModal');
                    } else {
                        // icon: 0:普通提示 1：正确的提示 2： 错误提示
                        // time: 不填默认1000ms
                        _this.showToast('没有可销售的优惠券', 0, 2000);
                    }
                }, err => { })
        },
        Coupon_change() {
            let _this = this;
            let index = _this.SellCouponsModalData.mainData.coupon;
            let data_source = _this.SellCouponsModalData.select_list[index];
            _this.currentCouponObj = deepCopyObj(_this.SellCouponsModalData.select_list[index]);
            _this.SellCouponsModalData.couponName = data_source.name 
            _this.SellCouponsModalData.mainData.couponTmpId = data_source.tmpId;
            _this.SellCouponsModalData.mainData.realPrice = data_source.realPrice;
            _this.SellCouponsModalData.mainData.originalPrice = data_source.originalPrice;
            _this.SellCouponsModalData.mainData.totalAvilableToBuy = !(Number(data_source.totalAvilableToBuy) == -1) ? data_source.totalAvilableToBuy : "无限";
            _this.SellCouponsModalData.mainData.maxBuyNum = data_source.maxBuyNum ? data_source.maxBuyNum : (!(Number(data_source.totalAvilableToBuy) == -1) ? data_source.totalAvilableToBuy : "无限");
        },
        SellCouponsModal_save() {
            //保存售卖优惠券
            var _this = this;
            var _params = _this.SellCouponsModalData.mainData;
            if (!_params.traderName) {
                _this.showToast('请先选择商家', 0, 2000);
            }
            if(_params.sellMoney!==0 && _params.sellMoney!=='0' && !_params.sellMoney){
                _params.sellMoney = _params.totalMoney
            }
            _this.$refs['SellCoupons_form'].validate((valid) => {
                if (valid) {
                    api.fetchGet('/coupon/sell/add.do', _params,{timeout:1000*60*5})
                        .then(res => {
                            if (res.resultCode == 0) {
                                _this.showToast(res.message, 1, 2000);
                                _this.closed('SellCouponsModal', 1);
                                _this.getItemList();
                            } else {
                                // icon: 0:普通提示 1：正确的提示 2： 错误提示
                                // time: 不填默认1000ms
                                _this.showToast('保存失败', 1, 2000);
                            }
                        }, err => { })
                }
            })

        },
        refundModal_open(list_data, title) {
            //退款谈话框 回收预购谈话框
            var _this = this;
            _this.refundModalData = {
                url: '/coupon/sell/refund.do',
                title: "退款",
                tmpName: list_data.tmpName,
                sellNum: list_data.sellNum,
                grantNum: list_data.grantNum,
                usedNum: list_data.usedNum,
                refundNum: list_data.leftNum,
                money: Number(list_data.sellMoney / list_data.sellNum * (list_data.leftNum)).toFixed(2),
                sellMoney: list_data.sellMoney,
                refundMoney: '',
                refundRemark: '',
            };
            _this.refundModalData = $.extend(list_data, _this.refundModalData)
            if (title == "回收预购") {
                _this.refundModalData.title = "回收预购";
                _this.refundModalData.url = '/coupon/sell/recycle.do';
            }
            _this.toOpenModal('refundModal', 1);
        },
        refundModal_save() {
            //保存退款
            var _this = this;
            var _params = _this.refundModalData;
            // 组装退款请求参数
            var _newParams = {
                id: _params.id,
                sellMoney: _params.sellMoney,
                payMoney: _params.sellMoney,
                actPayMoney : _params.sellMoney,
                refundMoney: _params.refundMoney,
                refundRemark: _params.refundRemark
            };
            _this.$refs['refund_form'].validate((valid) => {
                if (valid) {
                    api.fetchPost(_params.url, _newParams)
                        .then(res => {
                            if (res.resultCode == 0) {
                                _this.showToast(res.message, 1, 2000);
                                _this.closed('refundModal', 1);
                                _this.getList();
                            } else {
                                // icon: 0:普通提示 1：正确的提示 2： 错误提示
                                // time: 不填默认1000ms
                                _this.showToast('保存失败', 1, 2000);
                            }
                        }, err => { })
                }
            })
        },
        // 获取共选择用户的列表
        getTraderListModal_open() {
            let _this = this;
            let params = {
                page: _this.SelectMerchantsModalData.pageNumber,
                rp: _this.SelectMerchantsModalData.pageSize
            }
            api.fetchGet('/coupon/sell/getTraderListByPage.do', params)
                .then(res => {
                    _this.SelectMerchantsModalData.tbodysInfo = []
                    if (res.data.rows.length > 0) {
                        _this.SelectMerchantsModalData.tbodysInfo = res.data.rows;
                        _this.SelectMerchantsModalData.total = res.data.total;
                        _this.SelectMerchantsModalData.pageNumber = res.data.page;
                        _this.toOpenModal('SelectMerchantsModal');
                    } else {
                        // icon: 0:普通提示 1：正确的提示 2： 错误提示
                        // time: 不填默认1000ms
                        _this.showToast('没有已启用的商户', 0, 2000);
                    }
                }, err => { })
        },
        getReportDetailPagination(curPage, pageSize) {
            var _this = this;
            _this.SelectMerchantsModalData.pageNumber = curPage;
            _this.SelectMerchantsModalData.pageSize = pageSize ? pageSize : this.SelectMerchantsModalData.pageSize;
            var params = {
                page: _this.SelectMerchantsModalData.pageNumber,
                rp: _this.SelectMerchantsModalData.pageSize
            }
            api.fetchGet('/coupon/sell/getTraderListByPage.do', params)
                .then(res => {
                    if (res.data.rows.length > 0) {
                        _this.SelectMerchantsModalData.tbodysInfo = res.data.rows;
                        _this.SelectMerchantsModalData.total = res.data.total;
                        _this.SelectMerchantsModalData.pageNumber = res.data.page;
                    } else {
                        // icon: 0:普通提示 1：正确的提示 2： 错误提示
                        // time: 不填默认1000ms
                        _this.showToast('没有可销售的优惠券', 0, 2000);
                    }
                }, err => { })
        },
        SelectMerchantsModalData_change() {
            // 弹框搜索项
            var _this = this;
            _this.SelectMerchantsModalData.pageNumber = 1;
            var params = {
                page: _this.SelectMerchantsModalData.pageNumber,
                rp: _this.SelectMerchantsModalData.pageSize,
                name: _this.SelectMerchantsModalDataForm.name,
            }
            api.fetchGet('/coupon/sell/getTraderListByPage.do', params)
                .then(res => {
                    _this.SelectMerchantsModalData.tbodysInfo = res.data.rows;
                    _this.SelectMerchantsModalData.total = res.data.total;
                    _this.SelectMerchantsModalData.pageNumber = res.data.page;
                }, err => { })
        },
        handleEdit(index, row) {
            // 点击选择按钮时候执行
            this.SellCouponsModalData.mainData.traderName = row.name;
            this.SellCouponsModalData.mainData.traderId = row.id;
            this.closed('SelectMerchantsModal');
        },
        CouponListModal_open(sellBillId) {
            let self = this;
            self.exportDataid = sellBillId;
            let params = { 'sellBillId': sellBillId }
            api.fetchGet('/coupon/sell/getCodeList.do', params)
                .then(res => {
                    self.CouponListModalData.list = res.data;
                    this.toOpenModal('CouponListModal');
                }, err => { })
        },
        // 查看优惠券详情
        async SellCouponsModal_detail_open() {
            let _this = this;
            if (!_this.currentCouponObj) {
                _this.showToast('请先选择一个优惠券', 0, 2000);
                return;
            }
            let aparams = {
                id: _this.currentCouponObj.id
            }
            let bparams = {
                couponId: _this.currentCouponObj.id,
                sort: true
            }
            const [couponObjRes,merchantListRes] = await Promise.all([
                API.fetchGet('/coupon/detail.do',aparams),
                API.fetchGet('/coupon/getTrader2Sell.do',bparams)
            ])
            let initData = couponObjRes.data
            let selectedMerchant = []
            if(Array.isArray(merchantListRes.data)){
                merchantListRes.data.forEach(element=>{
                    if(element.checked){
                        selectedMerchant.push(element.name)
                    }
                })
            }
            var couponTypeId = function () {
                switch (initData.couponType) {
                    case "免费券":
                    return '0'
                    case "金额扣减券":
                    return '1'
                    case "金额折扣券":
                    return '2'
                    case "金额固定值券":
                    return '3'
                    case "时间券":
                    return '4'
                    case "不同计价券":
                    return '5'
                    default:
                    return null;
                }
            }();
            var couponRuleStr = function () {
                switch (initData.couponRule) {
                  case 0:
                    return '扣减前面时间'
                  case 1:
                    return '扣减后面时间'
                  case 2:
                    return '扣减进场时间和优惠时间计算的金额'
                  case 3:
                    return '扣减优惠时间和计费结束时间计算的金额'
                  default:
                    return null;
                }
            }();
            _this.SellCouponsModalData_detial = {
                id: null, 
                name: initData.name, //优惠券名称
                parkNameListStr: _this.currentCouponObj.parkNameListStr, //适用停车场
                balanceType: initData.balanceType, //销售结算
                sellFromTo: initData.sellFrom+' 至 '+ initData.sellTo, //可售卖时间
                validFromTo: initData.validFrom+' 至 '+ initData.validTo, //可发放时间
                validDay: initData.validDay, //使用有效期
                expireRefund: initData.expireRefund, //是否逾期退回
                couponTypeId: couponTypeId, // 券类型id
                couponTypeStr: initData.couponType, //券类型str
                couponRuleId: initData.couponRule, //扣减类型id
                couponRuleStr: couponRuleStr, //扣减类型str
                faceValue: initData.faceValue,
                originalPrice: initData.originalPrice, //优惠券原价
                realPrice: initData.realPrice, //折扣价
                useRule: initData.useRule.split('~')[0]+'元 - '+initData.useRule.split('~')[1]+'元', //使用条件
                totalNum: initData.totalNum ? initData.totalNum+'张' : '', //券总数
                isLimitTotal: initData.totalNum ? 0 : 1, //券数量是否有限(0:有限;1:无限)
                useParkingFee: initData.useParkingFee ? initData.useParkingFee : null, //享受免费时长(1:享受;0:不享受)
                financialParkIdStr: '', //财务主体str
                couponListStr: selectedMerchant.join(' / '), //可线上购买券的商户str
                isCover: initData.isCover, //是否可叠加(0:否;1:是)
                isCoverStr: initData.isCover ? '是' : '否',
                maxCoverNum: initData.maxCoverNum, //一次停车最多使用张数
                useParkingFee: initData.useParkingFee ? '享受' : '不享受', //是否享受免费时长
            };
            // 财务主体
            if(Array.isArray(_this.currentCouponObj.parkIdList)){
                _this.currentCouponObj.parkIdList.forEach((element,index)=>{
                    if(element==initData.financialParkId){
                        _this.SellCouponsModalData_detial.financialParkIdStr = _this.currentCouponObj.parkNameList[index]
                    }
                })
            }
            _this.toOpenModal('SellCouponsModal_detail');
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        //获取列表
        getItemList() {
            let self = this,
                params = {
                    page: this.pageNumber,
                    rp: this.pageSize
                };
            params = $.extend({}, params, self.otherParams, self.searchParams);
            api.fetchGet('/coupon/sell/getSellListByPage.do', params)
                .then(res => {
                    let data = res.data,
                        list = data.rows;
                    self.tbodysInfo = list;
                    self.total = data.total;
                }, err => { })
        },
        toBatchOprators(name, data) {
            switch (name) {
                case 'bt_correct': this.toAdjust(data); break;
                default: break;
            }
        },
        toAdjust() { },
        exportData() {
            let self = this;
            let params = {
                sellBillId: this.exportDataid,
            };
            params = $.extend({}, params);
            this.toExport('coupon/sell/exportCodeList.do', params);
        },
        exportPDF() {
            let self = this;
            if (!this.selectionList.length) {
                self.showToast('请选择一条记录');
                return false;
            }
            let ids = [];
            for (let i = 0; i < this.selectionList.length; i++) {
                ids.push(this.selectionList[i].id);
            }
            ids = ids.join(',');
            let params = {
                ids: ids
            }
            self.showDialog("确认导出纸质券?", '', function () {
                api.fetchGet('/coupon/sell/exportPDF.do', params,{timeout:1000*60*10}).then(res => {
                    let data = res;
                    self.showToast(data.message);
                    for (var i = 0; i < data.data.length; i++) {
                        var f = data.data[i];
                        var url = encodeURI("/mgr/common/download.do?fileName=" + f.tmpFileName + "&format=" + f.format + "&downName=" + f.downName);
                        self.downloadFile(url);
                    }
                }, err => { })
            });

        },
        exportSell() {
            let self = this;
            let theadsArr = []
            for(let i = 0; i<self.theadsInfo.length; i++){
            if(self.theadsInfo[i].checked){
                theadsArr.push(self.theadsInfo[i].prop)
            }
            }
            let params = {
            meterList: theadsArr.join(',')
            };
            params = $.extend({}, params, this.searchParams, this.otherParams);
            self.showDialog("确认导出该报表?", '', function () {
                self.toExportAsync('/coupon/sell/exportSell.do', params);
            });
        },
        exportCouponSn() {
            let self = this;
            if (!this.selectionList.length) {
                self.showToast('请选择一条记录');
                return false;
            }
            let ids = [];
            let refundNames = [];
            for (let i = 0; i < this.selectionList.length; i++) {
                if (this.selectionList[i].refundNum != null && this.selectionList[i].refundNum > 0) {
                    refundNames.push(this.selectionList[i].tmpName);
                }
                ids.push(this.selectionList[i].id);
            }
            if (ids.length === refundNames.length) {
                self.showToast('请至少选择一条未退款的记录');
                return false;
            }
            ids = ids.join(',');
            let params = {
                ids: ids
            }
            self.showDialog("确认导出未售优惠券编码?(其中" + refundNames.join(',') + "已退款，不导出)", '', function () {
                api.fetchGet('/coupon/sell/exportSellSn.do', params).then(res => {
                    let data = res;
                    self.showToast(data.message);
                    for (var i = 0; i < data.data.length; i++) {
                        self.showToast('导出成功', 0);
                        window.location.href = encodeURI("/mgr/common/download.do?fileName=" + res.data);
                    }
                }, err => { })
            });


        },
        batchRefund() {
            let self = this;
            if (!this.selectionList.length) {
                self.showToast('请选择一条记录');
                return false;
            }
            let ids = [];
            let refundNames = [];
            for (let i = 0; i < this.selectionList.length; i++) {
                if (this.selectionList[i].refundNum != null && this.selectionList[i].refundNum > 0) {
                    refundNames.push(this.selectionList[i].tmpName);
                } else {
                    ids.push(this.selectionList[i].id);
                }
            }
            if (ids.length == 0) {
                self.showToast('请至少选择一条未退款的记录');
                return false;
            }
            ids = ids.join(',');
            let params = {
                ids: ids
            }
            self.showDialog("确认要将勾选的售卖记录退款吗？", '', function () {
                api.fetchGet('/coupon/sell/batchRefund.do', params).then(res => {
                    let data = res;
                    self.showToast(data.message);
                    self.getList();
                }, err => { })
            });

        },
        downloadFile(url) {
            try {
                var elemIF = document.createElement("iframe");
                elemIF.src = url;
                elemIF.style.display = "none";
                document.body.appendChild(elemIF);
            } catch (e) {
            }
        },
        importSell() {
            var self = this;
            self.startImportResultTimer(self);
            self.toOpenModal('importModal');
        },
        startImportResultTimer(self) {
            function intervalFunc() {
                $.ajax({
                    url: '/mgr/coupon/sell/getImportResult.do',
                    dataType: "json",
                    data: {},
                    type: 'get',
                    success: function (result) {
                        if (result.status == 1) {
                            self.importResult = result.data;
                            if (!self.importResult || (self.importResult.totalCount == self.importResult.processedCount)) {
                                clearInterval(getImportResultTimer);
                                self.getList();
                            }
                        }
                    }
                });
            }
            intervalFunc();
            var getImportResultTimer = setInterval(function () {
                intervalFunc();
            }, 1000);
        },
        downloadTmp() {
            var self = this;
            let params = {
                "fileName": "import_sell_bill",
                "fileType": "xls"
            }
            $.ajax({
                url: '/mgr/importFlie/createExcelTmp.do',
                dataType: "json",
                data: params,
                type: 'get',
                success: function (result) {
                    var r = result;
                    if (r.success) {
                        if (r && r.success) {
                            self.showToast('下载成功', 1);
                            window.location.href = encodeURI("/mgr/common/templateDownload.do?fileName=" + r.fileName);
                        } else {
                            self.showToast('下载失败', 2);
                        }
                    }
                }
            });
        },
        downloadError() {
            var self = this;
            if (self.importResult.errorFileName != "") {
                window.location.href = encodeURI("/mgr/common/downloadNotDelete.do?fileName=" + self.importResult.errorFileName);
            }
        },
        sureImport(event) {
            var self = this;
            event.preventDefault();
            var formData = new FormData();
            formData.append("importFile", self.importFile.importFile);
            if (!this.importFile.importFile) {
                self.showToast('请先选择文件', 1)
                return false;
            }
            var objtype = this.importFile.importFile.name.substring(this.importFile.importFile.name.lastIndexOf(".")).toLowerCase();
            if (objtype != '.xls') {
                self.showToast('只支持xls格式文件', 1)
                return false;
            }
            api.fetchPost('/coupon/sell/batchImport.do', formData).then(res => {
                //start
                var data = res;
                if (res.status == 1) {
                    self.importFile.importFile = '';
                    $("#fileInput").val('')
                    setTimeout(function () {
                        self.startImportResultTimer(self);
                    }, 1000);
                }
            }, err => { });
        },
        getFile(event) {
            this.importFile.importFile = event.target.files[0];
        }

    },
    filters: {
        totalNumShow: function (value) {
            if (value == 0) {
                return "无限";
            }
            return value;
        }
    }

}